//
//  AlertsController.m
//  gdemm
//
//  Created by 乔明超 on 16/9/20.
//  Copyright © 2016年 Goldencis. All rights reserved.
//

#import "AlertsController.h"
#import "AlertTableViewCell.h"
#import "CustomButton.h"
#import "MessageManager.h"
#import "UserDefaultsUtil.h"
#import "MessageInfo.h"
#import "ToastManager.h"
#import "MJRefresh.h"
#import "Utils.h"
#import "AlertsDetailController.h"
#import "UITabBar+RedDotBadge.h"
#import "SVProgressHUD.h"

@interface AlertsController ()
@property (strong,nonatomic) NSMutableArray *messageArray;
@property (strong,nonatomic) NSMutableArray *deleteMessageArray;
@property (strong,nonatomic) CustomButton *mBtnDelete;
@property(nonatomic,strong)UIView *coverView;
@property(nonatomic,assign)BOOL redFlag;
@property(nonatomic,strong) NSOperationQueue * queue;
@end

@implementation AlertsController
static NSString *identifier = @"alerts";
#pragma mark - 懒加载
-(UIView *)coverView{
    if (_coverView == nil) {
        _coverView = [[UIView alloc]initWithFrame:CGRectMake(0, WINDOWHEIGHT-176-49, WINDOWWIDTH, 176)];
        _coverView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
        self.mBtnDelete.x = _coverView.centerX ;
        self.mBtnDelete.y = 50;
        [_coverView addSubview:self.mBtnDelete];
        if (![DeviceTypeJudge isPadDeviceType]) {
            _coverView.frame = CGRectMake(0, WINDOWHEIGHT-150*KHeightScale, WINDOWWIDTH, 101*KHeightScale);
            self.mBtnDelete.x = _coverView.centerX;
            self.mBtnDelete.y = 30;
        }
    }
    return _coverView;
}
//添加删除按钮
- (CustomButton *)mBtnDelete{
    if (_mBtnDelete == nil) {
        _mBtnDelete = [CustomButton buttonWithType:UIButtonTypeSystem];
        //        _mBtnCrush.x = self.view.centerX;
        //        _mBtnCrush.y = CGRectGetMaxY(self.view.frame) - 150;
        [_mBtnDelete setImage:[[Utils imageWithKey:@"other_icon_delete"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
        [_mBtnDelete setTitle:NSLocalizedString(@"str_delete", @"删除") forState:UIControlStateNormal];
        [_mBtnDelete setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [_mBtnDelete addTarget:self action:@selector(crushHandler:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    return _mBtnDelete;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(skinSwitchHandler) name:@"skinswitch" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(reloadAlertsData) name:@"AlertsReloadData" object:nil];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editBarButtonItemHnadler)];
    [self setupTableView];
    __weak __typeof(self) weakSelf = self;
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//           
//        });
        [[MessageManager getInstance]loadCloundFileInfo:NO];
        weakSelf.messageArray = [[MessageManager getInstance] getAllMessages:[[UserDefaultsUtil shareInstance]getString:LC_USERGUID]];
        if ([weakSelf.navigationItem.title isEqualToString: NSLocalizedString(@"str_multi_select", @"多选")]) {
            for (MessageInfo *messageInfo in self.messageArray) {
                messageInfo.selState = YES;
            }
        }
        [weakSelf cancelBarButtonItemHnadler];
        [weakSelf reloadAlertsData];
        [weakSelf.tableView.mj_header endRefreshing];
    }];
    
}

-(void)reloadAlertsData{
    NSBlockOperation * reloadDataOperation  = [NSBlockOperation blockOperationWithBlock:^{
        [self.tableView reloadData];
    } ];
    NSBlockOperation * addRedflagOperation = [NSBlockOperation blockOperationWithBlock:^{
        self.redFlag = NO;
        [self.messageArray enumerateObjectsUsingBlock:^(MessageInfo * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (!obj.isRead) {
                self.redFlag = YES;
                *stop  = YES;
            }
        }];
        if (self.redFlag) {
            [self.tabBarController.tabBar showBadgeOnItemIndex:3];
        }else{
            [self.tabBarController.tabBar hideBadgeOnItemIndex:3];
        }
    } ];
    
    [addRedflagOperation addDependency:reloadDataOperation];
    
    self.queue = [NSOperationQueue mainQueue];
    [self.queue addOperation:reloadDataOperation];
    [self.queue addOperation:addRedflagOperation];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:[DeviceTypeJudge getTitleFont]]} forState:UIControlStateNormal];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self cancelBarButtonItemHnadler];
}
#pragma mark - 加载所有消息
- (void)loadMessageAllInfos{
    [[MessageManager getInstance]loadCloundFileInfo:NO];
    self.messageArray = [[MessageManager getInstance] getAllMessages:[[UserDefaultsUtil shareInstance]getString:LC_USERGUID]];
    [self reloadAlertsData];
}
#pragma mark - 初始化tableView
- (void)setupTableView{
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadMessageAllInfos];
    });
}
#pragma mark - navigationBar右侧点击事件
- (void)editBarButtonItemHnadler{
    if (self.messageArray.count == 0) {
        [self.view makeToast:NSLocalizedString(@"str_noOperationalMessages", @"当前没有可操作消息通知")];
        return;
    }
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelBarButtonItemHnadler)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:[DeviceTypeJudge getTitleFont]]} forState:UIControlStateNormal];
    self.navigationItem.title = NSLocalizedString(@"str_multi_select", @"多选");
    for (MessageInfo *messageInfo in self.messageArray) {
        messageInfo.selState = YES;
    }
    [self.tabBarController.view addSubview:self.coverView];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 176+49, 0);
    //self.tableView.mj_header.hidden = YES;
    [self reloadAlertsData];
    
    
}

- (void)cancelBarButtonItemHnadler{
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editBarButtonItemHnadler)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:[DeviceTypeJudge getTitleFont]]} forState:UIControlStateNormal];
    self.navigationItem.title = NSLocalizedString(@"str_alerts", @"消息");
    for (MessageInfo *messageInfo in self.messageArray) {
        messageInfo.selState = NO;
    }
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.coverView removeFromSuperview];
    //self.tableView.mj_header.hidden = NO;
    [self reloadAlertsData];
    
}

#pragma mark - 粉碎消息信息
- (void)crushHandler:(UIButton *)sender{
    NSInteger count = 0;
    for (MessageInfo *messageInfo in self.messageArray) {
        if (messageInfo.selected) {
            count++;
            break;
        }
    }
    
    if (count != 0) {
        [self showDialog];
        
    }else{
        [[UIApplication sharedApplication].delegate.window makeToast:NSLocalizedString(@"str_selectOneMessageDeletedAtLeast", @"请至少选择一个需要删除的消息")];
    }
}

- (void)showDialog{
    
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"str_deleteSelectedMessages", @"删除所选的消息")  message:nil preferredStyle:UIAlertControllerStyleAlert];
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:self.messageArray];
    UIAlertAction *confirm = [UIAlertAction actionWithTitle:NSLocalizedString(@"str_ok", @"确定") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        for (MessageInfo *messageInfo in tempArray) {
            if (messageInfo.selected) {
                long ID = messageInfo.ID;
                [self.messageArray removeObject:messageInfo];
                [[MessageManager getInstance]deleteMessageById:ID];
            }
        }
        [self loadMessageAllInfos];
        [self cancelBarButtonItemHnadler];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"str_cancel", @"取消") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alertVc addAction:confirm];
    [alertVc addAction:cancel];
    [self.navigationController presentViewController:alertVc animated:YES completion:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.messageArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AlertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    MessageInfo *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
    if (cell == nil) {
        cell = [[AlertTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.messageInfo = messageInfo;
    cell.lineView.backgroundColor = [Utils colorWithKey:@"mainLineColor"];
    cell.detailLable.textColor = [Utils colorWithKey:@"detailLableColor"];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageInfo *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
    if (messageInfo.selState == NO) {
        messageInfo.isRead = YES;
        [[MessageManager getInstance]setReadedById:messageInfo.ID];
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
        UIStoryboard * story = [UIStoryboard storyboardWithName:@"AlertsDetailController" bundle:nil];
        
        AlertsDetailController *alertsDetailVc =  story.instantiateInitialViewController;
        
        alertsDetailVc.messageInfo = messageInfo;
        [self.navigationController pushViewController:alertsDetailVc animated:YES];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"read" object:nil];
    }else{
        messageInfo.selected = !messageInfo.selected;
        [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (![DeviceTypeJudge isPadDeviceType]) {
        return 62*KHeightScale;
    }
    return 80;
}
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath{
    MessageInfo *messageInfo = [self.messageArray objectAtIndex:indexPath.row];
    
    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [[MessageManager getInstance]deleteMessageById:messageInfo.ID];
        [self loadMessageAllInfos];
        
    }];
    deleteAction.backgroundColor = [Utils UIColorFromHex:0XEB4743];
    NSArray *arr = @[deleteAction];
    return arr;
}

/**
 *  肤色切换
 */

- (void)skinSwitchHandler{
    [self.tableView reloadData];
    self.tabBarItem.selectedImage = [[Utils imageWithKey:@"tabBar_alerts_click_icon"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.coverView.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    self.view.backgroundColor = [Utils colorWithKey:@"mainBgColor"];
    [self.mBtnDelete setImage:[[Utils imageWithKey:@"other_icon_delete"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal ] forState:UIControlStateNormal];
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
@end
